package com.qf.web.controller;

import com.alibaba.fastjson.JSON;
import com.qf.domain.User;
import com.qf.domain.WeiXinResult;
import com.qf.service.OrederService;
import com.qf.service.impl.OrederServiceImpl;
import com.qf.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/paySuccess")
public class PaySuccessServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");//设置编码
        //判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return ;
        }
        //获取前端数据
        String result = request.getParameter("result");
        if(StringUtil.isEmpty(result)){
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return;
        }
        //处理结果 、
        //把json字符串转成java对象
        WeiXinResult weiXinResult = JSON.parseObject(result, WeiXinResult.class);
        //判断
        String oid = weiXinResult.getResult().getOut_trade_no();
        if(weiXinResult.getResult().getResult_code().equals("SUCCESS")){
            //判断重订向还是对点通讯
            if(weiXinResult.getType()==0){
                //修改订单状态
                OrederService orderService = new OrederServiceImpl();
                orderService.updateState(oid,2);
                request.setAttribute("msg",oid+"已支付成功！正在给你发货呢");
                request.getRequestDispatcher("/message.jsp").forward(request,response);

            }else if(weiXinResult.getType()==1){
                System.out.println("点对点通讯");
            }else{
                request.setAttribute("msg",oid+"付款失败了");
                request.getRequestDispatcher("/message.jsp").forward(request,response);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
